package transport.handler;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import queue.TaskQueue;
import service.ResponseService;
import transport.protocol.MessageHolder;

import java.util.concurrent.BlockingQueue;

/**
 *
 * Created by sunny on 17-9-13.
 */
@Component
public class AcceptorHandler extends ChannelInboundHandlerAdapter {

    private static Logger logger = Logger.getLogger(AcceptorHandler.class);

    private final BlockingQueue<MessageHolder> taskQueue;

    public AcceptorHandler() {
        taskQueue = TaskQueue.getQueue();
    }

    @Autowired
    ResponseService responseService;

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        logger.info("有新链接");
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {

        if (msg instanceof MessageHolder) {
            logger.info("接受到新请求：" + msg.toString());

            MessageHolder messageHolder = (MessageHolder) msg;
            messageHolder.setChannel(ctx.channel());

            if (!taskQueue.add(messageHolder)) {
                logger.warn("服务器繁忙，拒绝服务");
                responseService.serverBusy(ctx.channel(), messageHolder.getType());
            } else {
                logger.info("TaskQueue添加任务: taskQueue=" + taskQueue.size());
            }
        } else {
            throw new IllegalArgumentException("msg is not instance of MessageHolder");
        }
    }
}
